package com.wbk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wbk.constant.RedisConstant;
import com.wbk.dao.SetmealDao;
import com.wbk.entity.PageResult;
import com.wbk.entity.QueryPageBean;
import com.wbk.pojo.CheckGroup;
import com.wbk.pojo.Setmeal;
import com.wbk.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Value("${out_put_path}")
    private String outPutPath;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Override
    public void add(Setmeal setmeal,Integer[] checkgroupIds) {
        //插入套餐信息
        setmealDao.add(setmeal);
        //设置套餐和检查组多对多关系
        Integer setmealId = setmeal.getId();
        System.out.println("id:"+setmealId);
        setSetmealAndCheckGroup(setmealId,checkgroupIds);
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());

        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    public void generateMobileStaticHtml(){
        List<Setmeal> setmealList = setmealDao.findAll();
        //生成套餐列表静态页面
        generateSetmealList(setmealList);
        //生成套餐详情静态页面（多个）
        generateSetmealDetail(setmealList);
    }

    public void generateSetmealList(List<Setmeal> setmealList){
        Map<String,Object> map=new HashMap<>();
        map.put("setmealList",setmealList);
        generateHTML("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    public void generateSetmealDetail(List<Setmeal> setmealList){
        Map<String,Object> map=new HashMap<>();
        for (Setmeal setmeal:setmealList){
            map.put("setmeal",setmealDao.findById(setmeal.getId()));
            generateHTML("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    //通用生成静态页面方法
    public void generateHTML(String ftlName,String outFileName,Map<String,Object> map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out=null;
        try {
            Template template = configuration.getTemplate(ftlName);
            out=new FileWriter(new File(outPutPath+"\\"+outFileName));
            template.process(map,out);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Setmeal>setmealList = page.getResult();
        return new PageResult(total,setmealList);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic){
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
    }

    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        Map<String,Integer> map = new HashMap<>();
        if (checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                map.put("setmeal_id",id);
                map.put("checkgroup_id",checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }
}
